# -*- coding: utf-8 -*-
# Python中默认的编码格式是 ASCII 格式，在没修改编码格式时无法正确打印汉字，所以在读取中文时会报错。

import time, threading

balance = 0

def change_it(n):

    # 先存后取，结果应该为0:
    global balance
    balance = balance + n
    balance = balance - n

# def run_thread(n):
#     for i in range(2000000):
#         change_it(n)

# t1 = threading.Thread(target=run_thread, args=(5,))
# t2 = threading.Thread(target=run_thread, args=(8,))
# t1.start()
# t2.start()
# t1.join()
# t2.join()
# print(balance)


# 但是t1和t2是交替运行的，如果操作系统以下面的顺序执行t1、t2:
#
# 初始值 balance = 0
#
# t1: x1 = balance + 5  # x1 = 0 + 5 = 5
#
# t2: x2 = balance + 8  # x2 = 0 + 8 = 8
# t2: balance = x2      # balance = 8
#
# t1: balance = x1      # balance = 5
# t1: x1 = balance - 5  # x1 = 5 - 5 = 0
# t1: balance = x1      # balance = 0
#
# t2: x2 = balance - 8  # x2 = 0 - 8 = -8
# t2: balance = x2      # balance = -8
#
# 结果 balance = -8


# 当多个线程同时执行lock.acquire()时，只有一个线程能成功地获取锁，
# 然后继续执行代码，其他线程就继续等待直到获得锁为止。
#
# 获得锁的线程用完后一定要释放锁，否则那些苦苦等待锁的线程将永远等待下去，
# 成为死线程。所以我们用try...finally来确保锁一定会被释放。

lock = threading.Lock()

def run_thread(n):

    for i in range(100):
        # 先要获取锁:
        lock.acquire()
        try:
            # 放心地改吧:
            change_it(n)
        finally:
            # 改完了一定要释放锁:
            lock.release()






